package com.miao.im.support.disruptor;

import com.lmax.disruptor.WorkHandler;
import com.miao.im.service.message.ChatMessage;
import com.miao.im.service.message.OfflineMessageManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/18 13:43
 * @Description:
 */
@Component
@Slf4j
public class DisruptorEventBus implements WorkHandler<DisruptorEvent<?>> {
    @Autowired
    private OfflineMessageManager messageManager;

    @Override
    public void onEvent(DisruptorEvent<?> event) throws Exception {
        Object payload = event.getPayload();
        if (payload == null) {
            return;
        }
        try {
            switch (event.getEventType()) {
                case SAVE_OFFLINE_MSG:
                    if (payload instanceof ChatMessage) {
                        ChatMessage message = (ChatMessage) payload;
                        messageManager.save(message)
                                .doOnError(throwable -> log.error("执行disruptor bus异常:", throwable))
                                .subscribe();
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            log.error("执行disruptor bus异常:", e);
        }
    }
}
